import { ref, computed } from "vue";

/**
 * 转化为tree
 */
function treeToArray(tree: Object, customN: string, tableRef: any, isSelected: any) {
  // departmentModels
  return tree.reduce((res, item) => {
    const { ...i } = item;
    const children = item[customN];
    console.log(isSelected.value);
    tableRef.value!.toggleRowSelection(item, isSelected.value);
    return res.concat(i, children && children.length ? treeToArray(children, customN, tableRef, isSelected) : []);
  }, []);
}

/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * */
export const useSelection = (rowKey: string = "id", attrs: any, tableRef: any) => {
  const isSelected = ref<boolean>(false);
  const selectedList = ref<{ [key: string]: any }[]>([]);

  // 当前选中的所有 ids 数组
  const selectedListIds = computed((): string[] => {
    let ids: string[] = [];
    selectedList.value.forEach(item => ids.push(item[rowKey]));
    return ids;
  });

  /**
   * @description 多选操作
   * @param {Array} rowArr 当前选择的所有数据
   * @return void
   */
  const selectionChange = (rowArr: { [key: string]: any }[]) => {
    rowArr.length ? (isSelected.value = true) : (isSelected.value = false);
    if (attrs && attrs["tree-props"] && attrs["tree-props"].children) {
      rowArr = treeToArray(rowArr, attrs["tree-props"].children, tableRef, isSelected);
      // 选中
      // rowArr.forEach(item => {
      //   tableRef.value!.toggleRowSelection(item, isSelected.value);
      // });
    }
    // console.log(rowArr, tableRef.value);
    selectedList.value = rowArr;
  };

  return {
    isSelected,
    selectedList,
    selectedListIds,
    selectionChange
  };
};
